<template>
  <div>

    <el-form class="d" autoComplete="on" :model="loginForm" :rules="loginRules" ref="loginForm" label-position="left">
      <div class="formGroup">
        <el-form-item prop="username">
          <el-input size="medium" @keyup.enter.native="handleLogin" v-model="loginForm.username" auto-complete="off" placeholder="请输入用户名">
            <svg-icon slot="prefix" icon-class="account"></svg-icon>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input size="medium" @keyup.enter.native="handleLogin" :type="pwdType" v-model="loginForm.password" auto-complete="off" placeholder="请输入密码">
            <i class="el-icon-view el-input__icon" slot="suffix" @click="showPwd"></i>
            <svg-icon slot="prefix" icon-class="password"></svg-icon>
          </el-input>
        </el-form-item>
        <el-form-item prop="code">
          <el-input size="medium" v-model="loginForm.code" placeholder="请输入验证码" class="identifyinput"></el-input>
        </el-form-item>
        <el-form-item>
          <div class="identifybox">
            <div @click="refreshCode">
              <img id="myCode" src=""></img>
            </div>
            <el-button @click="refreshCode" type='text' class="textbtn">看不清，换一张</el-button>
          </div>
        </el-form-item>
<!--
        <div class="remFor">
          <a href="'https://blog.csdn.net/Vanadis_outlook/article/details/72823024.html'" class="forget">忘记密码？</a>
        </div>
-->
        <div class="formButton">
          <el-form-item style="width:100%;">
            <el-button type="primary" size="mini" style="width:100%;" :loading="loading" @keyup.enter.native="keyupLogin" @click.native.prevent="handleLogin">登录</el-button>
          </el-form-item>
        </div>

      </div>
    </el-form>
  </div>
</template>

<script>
import { isvalidUsername } from "@/utils/validate";

export default {
  name: "login",
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!isvalidUsername(value)) {
        callback();
      } else {
        callback(new Error("请输入正确的用户名"));
      }
    };
    const validatePass = (rule, value, callback) => {
      if (value.length < 5) {
        callback(new Error("密码不能小于5位"));
      } else {
        callback();
      }
    };
    const validateVerifycodes = (rule, value, callback) => {
      if (value.length < 0) {
        callback(new Error("请输入验证码"));
      }else if(value.length > 4){
        callback(new Error("请输入4位数验证码"));
      } else {
        callback();
      }
    };
    return {
      loginForm: {
        username: "",
        password: "",
        code: "",
        randomStr: "",
      },
      loginRules: {
        username: [
          {
            required: true,
            trigger: "blur",
            validator: validateUsername,
          },
        ],
        password: [
          {
            required: true,
            trigger: "blur",
            validator: validatePass,
          },
        ],
        code: [
          {
            required: true,
            trigger: "blur",
            validator: validateVerifycodes,
          }
        ]
      },
      loading: false,
      pwdType: "password",
      note: {
        position: "relative",
        width: "100%",
        height: "100%",
        backgroundImage: "url(" + require("../../assets/bg.png") + ")",
        backgroundSize: "100% 100%",
        backgroundRepeat: "no-repeat",
      },
      canClick: true
    };
  },
  mounted() {
    this.refreshCode();
    this.keyDownKeybord();
  },
  methods: {
    keyDownKeybord() {
      let that = this;
      let key;
      document.onkeydown = function (e) {
        if (window.event == undefined) {
          key = e.keyCode;
        } else {
          key = window.event.keyCode;
        }
        if (key == 13) {
          that.keyupLogin();
        }
      };
    },
    keyupLogin(e) {
      this.handleLogin();
    },
    showPwd() {
      if (this.pwdType === "password") {
        this.pwdType = "";
      } else {
        this.pwdType = "password";
      }
    },
    handleLogin() {
      console.log(this.canClick)
      this.$refs.loginForm.validate((valid) => {
        if (valid && this.canClick) {
          this.canClick = false
          this.loading = true;
          this.loginForm.password = this.loginForm.password;
          this.$store
            .dispatch("Login", this.loginForm)
            .then(() => {
              //this.canClick = true;
              //this.loading = false;
              this.$router.push({
                path: "/",
              });
            })
            .catch((res) => {
              this.canClick = true
              this.loginForm.code = "";
              this.refreshCode();
              this.loading = false;
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 切换验证码
    refreshCode() {
      this.getRandomStr();
      var url = process.env.BASE_API;
      document
        .getElementById("myCode")
        .setAttribute(
          "src",
          url + "/code/image?randomStr=" + this.loginForm.randomStr
        );
    },
    getRandomStr() {
      var chars = [
        "0",
        "1",
        "2",
        "3",
        "4",
        "5",
        "6",
        "7",
        "8",
        "9",
        "A",
        "B",
        "C",
        "D",
        "E",
        "F",
        "G",
        "H",
        "I",
        "J",
        "K",
        "L",
        "M",
        "N",
        "O",
        "P",
        "Q",
        "R",
        "S",
        "T",
        "U",
        "V",
        "W",
        "X",
        "Y",
        "Z",
      ];
      var res = "";
      for (var i = 0; i < 5; i++) {
        var id = Math.ceil(Math.random() * 35);
        res += chars[id];
      }
      this.loginForm.randomStr = res;
    },
  },
};
</script>

<style lang="scss" scoped>
label {
  width: 70px;
  text-align: left;
}

.form-control {
  width: 270px;
  flex: 1;
  -webkit-flex: 1;
  -ms-flex: 1;
}
.remember {
  width: 250px;
  text-align: left;
}
.forget {
  width: 500px;
  text-align: right;
  font-size: 14px;
  font-family: PingFang SC;
}
.remFor {
  margin-bottom: 10px;
  padding-bottom: 10px;
}
.tabsUser {
  display: inline-block;
  margin-left: 0px;
  margin-right: 0px;
  text-align: center;
  font-size: 25px;
}
.identifybox {
  display: flex;
  justify-content: space-between;
  margin-top: 0;
  margin-left: -7px;
}
.el-form-item__error {
  padding-top: 0px;
}
.el-form-item {
  margin-bottom: 15px;
}
</style>
